<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\StoreBespeakCate;
use App\Http\Requests\UpdatePrefer;
use App\Models\Bespeak;
use App\Models\BespeakCate;
use App\Models\Pack;
use App\Models\PreferCate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PreferCateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function __construct()
    {
        view()->share([
            '_hd' => 'am-in',
            '_preferCate' => 'am-active',
        ]);

    }
    public function index()
    {


      $cates= PreferCate::orderBy('sort')->paginate(15);

        return view('admin.preferCate.index',compact('cates'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.preferCate.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreBespeakCate $request)
    {


        PreferCate::create($request->all());
        return redirect('/admin/preferCate')->with('success', '新增成功~');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $preferCate=PreferCate::find($id);
        return view('admin.preferCate.edit',compact('preferCate'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatePrefer $request, $id)
    {
       $preferCate=PreferCate::find($id);
       $preferCate->update($request->all());
        return redirect('/admin/preferCate')->with('success', '编辑成功~');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {


        $data['Pcates_id']=$id;
        $good=Pack::where($data)->first();
        if($good){
            return back()->with('success','该分类下还有项目，若要删除分类，请先删除分类下的商品');
        }
        PreferCate::destroy($id);
        return back()->with('success','删除成功');
    }
//ajax排序


    public function sort(Request $request){
        $cate = PreferCate::find($request->id);
        $cate->sort = $request->sort;
        $cate->save();
    }
}
